# -*- coding:utf-8 -*-
from flask_httpauth import HTTPTokenAuth
from flask import current_app, g
from itsdangerous import TimedJSONWebSignatureSerializer as JWT
auth = HTTPTokenAuth(scheme='Bearer')


def get_secret_key():
    a_pp = current_app._get_current_object()
    secret_key = a_pp.config['SECRET_KEY']
    return secret_key


def create_token(uid):
    '''
    生成token
    '''
    if uid:
        jwt = JWT(get_secret_key(), expires_in=3600)
        return jwt.dumps({'uid': uid})
    return '请带上uid这个参数'


@auth.verify_token
def verify_token(token):
    '''
    HTTPTokenAuth 的重点在于token的验证，通过用户名和密码生成token并保存到一个地方，
    在这个方面里去验证用户传过来token的合法性
    '''
    jwt = JWT(get_secret_key(), expires_in=3600)
    # users = ['john', 'susan']

    # for user in users:
    #     token_ = jwt.dumps({'username': user})
    #     print('*** token for {}: {}\n'.format(user, token_))
    # g.user = None
    try:
        data = jwt.loads(token)
    except:
        return False
    if 'uid' in data:
        g.user = data['uid']
        return True
    return False
